package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Result queryTypeList() {
        String key = "shop_type";
//        //1、查询Redis中的缓存数据
//        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
//        String shopList = value.get(key);
//        if (shopList != null) {
//            return Result.ok(shopList);
//        }
//        //2。查询数据库中的数据
//        List<ShopType> list = this.list();
//        if (list.size() == 0 || list.isEmpty()) {
//            return Result.fail("查询结果为空");
//        }
//        String jsonPrettyStr = JSONUtil.toJsonPrettyStr(list);
//        value.set(key, jsonPrettyStr);
        ListOperations listops = redisTemplate.opsForList();
        List<ShopType> range = listops.range(key, 0, -1);
        if (range != null) {
            return Result.ok(range);
        }
        List<ShopType> list = this.list();
        if (list.size() == 0 || list.isEmpty()) {
            return Result.fail("查询结果为空");
        }
        listops.rightPushAll(key, list);
        return Result.ok(list);
    }
}
